@echo off
REM HomeBox Single Binary Build Script for Windows
REM This script builds HomeBox as a single executable with embedded frontend
REM Usage: In PowerShell, run: .\build-single-binary.bat

echo Building HomeBox Single Binary...
echo.

REM Build frontend first
echo 📦 Building frontend...
cd frontend

REM Install dependencies and build
call pnpm install
if errorlevel 1 (
    echo ❌ Failed to install frontend dependencies
    pause
    exit /b 1
)

call pnpm run build
if errorlevel 1 (
    echo ❌ Frontend build failed
    pause
    exit /b 1
)

REM Check if build was successful
if not exist ".output\public" (
    echo ❌ Frontend build failed - .output\public directory not found
    pause
    exit /b 1
)

echo ✅ Frontend built successfully
echo.

REM Copy frontend assets to backend
echo 📁 Copying frontend assets to backend...
cd ..
if exist "backend\app\api\static\public" rmdir /s /q "backend\app\api\static\public"
mkdir "backend\app\api\static\public"
xcopy /s /e /y "frontend\.output\public\*" "backend\app\api\static\public"
if errorlevel 1 (
    echo ❌ Failed to copy frontend assets
    pause
    exit /b 1
)

echo ✅ Frontend assets copied successfully
echo.

REM Generate API docs (optional step)
echo 📚 Generating API documentation...
cd backend

REM Install swag if not exists
where swag >nul 2>nul
if errorlevel 1 (
    echo Installing swag...
    go install github.com/swaggo/swag/cmd/swag@latest
    if errorlevel 1 (
        echo ❌ Failed to install swag. Skipping API docs generation.
        goto build_binary
    )
)

REM Generate swagger docs
swag fmt --dir=.\app\api
if errorlevel 1 (
    echo ❌ Failed to format API docs. Skipping API docs generation.
    goto build_binary
)

swag init --dir=.\app\api,.\internal\core\services,.\internal\data\repo --parseDependency --output .\app\api\static\docs
if errorlevel 1 (
    echo ❌ Failed to generate API docs. Skipping API docs generation.
    goto build_binary
)

echo ✅ API documentation generated successfully
echo.

:build_binary
REM Build single binary
echo 🔨 Building single binary...

REM Build for Windows
go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ..\homebox.exe .\app\api
if errorlevel 1 (
    echo ❌ Build failed
    pause
    exit /b 1
)

echo ✅ Single binary build completed!
echo 📦 Binary location: %CD%\..\homebox.exe
echo.
echo 🚀 Ready to run! Use: .\homebox.exe
echo.
pause